package com.richie696.bank.utils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 工具类：应答操作/结果发送工具类
 *
 * @author 王锦阳
 * @version 1.3
 * @since 2013年7月3日 下午8:36:49
 */
public final class WebUtils {

    //限定检查周期内的最大请求次数
    private final static int MAX_REQUEST_RATE = 50;
    //限定的检查周期时间 1min
    private final static int REQUEST_RATE_DURATION = 60000;

    private WebUtils() {
    }

    /**
     * 方法：以标准JSON对象格式发送结果的方法
     *
     * @param response Servlet 应答对象
     * @param obj      需要应答的内容
     * @throws IOException 当往客户端发送数据出现问题时抛出该异常
     * @author 王锦阳
     */
    public static void sendJsonResult(HttpServletResponse response, Object obj) throws IOException {
        setJSONContentType(response);
        response.getWriter().print(JsonUtils.serialize(obj));
    }

    /**
     * 方法：以标准HTML页面格式发送结果的方法
     *
     * @param response Servlet 应答对象
     * @param obj      需要应答的内容
     * @throws IOException 当往客户端发送数据出现问题时抛出该异常
     * @author 王锦阳
     */
    public static void sendResult(HttpServletResponse response, Object obj) throws IOException {
        setContentType(response);
        response.getWriter().print(JsonUtils.serialize(obj));
    }

    /**
     * 方法：设置text/html标准HTML文档响应类型
     *
     * @param response 应答对象
     * @author 王锦阳
     */
    public static void setContentType(HttpServletResponse response) {
        response.setContentType("text/html;charset=" + StandardCharsets.UTF_8.name());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Charset", StandardCharsets.UTF_8.name());
        response.setHeader("Cache-Control", "no-cache");
    }

    /**
     * 方法：设置application/json标准JSON串响应类型
     *
     * @param response 应答对象
     * @author 王锦阳
     */
    public static void setJSONContentType(HttpServletResponse response) {
        response.setContentType("application/json;charset=" + StandardCharsets.UTF_8.name());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Charset", StandardCharsets.UTF_8.name());
        response.setHeader("Cache-Control", "no-cache");
    }

    /**
     * 获取远端客户端IP地址
     *
     * @param request http请求
     * @return 客户端IP地址，获取不到返回null
     */
    public static String getRemoteIP(HttpServletRequest request) {
        String remoteAddr = null;
        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }
        return remoteAddr;
    }

}
